package com.socialsoftware.Page;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.socialsoftware.R;
import com.socialsoftware.api.ApiError;
import com.socialsoftware.api.ApiService;
import com.socialsoftware.model.User;
import com.socialsoftware.repository.ContactRepository;
import com.socialsoftware.repository.FriendRequestRepository;
import com.socialsoftware.util.SessionManager;
import com.socialsoftware.MediaCommunication.service.CallService;
import com.socialsoftware.MediaCommunication.service.WebSocketService;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final int MAX_LOGIN_ATTEMPTS = 5;
    private static final long LOCKOUT_DURATION_MS = 30000; // 30秒锁定时间
    private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_]{4,20}$");
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^[a-zA-Z0-9_!@#$%^&*]{6,20}$");
    private TextInputLayout tilUsername;
    private TextInputLayout tilPassword;
    private TextInputEditText etUsername;
    private TextInputEditText etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private ProgressBar progressBar;
    private TextView tvLoginAttempts;
    private ConstraintLayout mainContainer;
    private SessionManager sessionManager;
    private ContactRepository contactRepository;
    private FriendRequestRepository friendRequestRepository;
    private ApiService apiService;
    private int loginAttempts = 0;
    private CountDownTimer lockoutTimer;
    private boolean isLocked = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        sessionManager = SessionManager.getInstance(getApplicationContext());
        if (sessionManager.isLoggedIn()) {
            if (sessionManager.isSessionValid()) {
                Log.e("登录页面", "拨打方"+sessionManager.getUser());
                // 初始化WebRTC并连接信令服务器，使用用户名
                initializeMediaCommunication(sessionManager.getUser().getUsername());
                startMainActivity();
                return;
            } else {
                // 注销登录
                cleanupMediaCommunication();
                sessionManager.logout();
            }
        }
        contactRepository = new ContactRepository(getApplication());
        friendRequestRepository = new FriendRequestRepository(getApplication());
        apiService = new ApiService(sessionManager);
        initializeViews();
        setupListeners();
    }
    private void initializeViews() {
        mainContainer = findViewById(R.id.container);
        tilUsername = findViewById(R.id.tilUsername);
        tilPassword = findViewById(R.id.tilPassword);
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tvRegister);
        progressBar = findViewById(R.id.progressBar);
        tvLoginAttempts = new TextView(this);
        tvLoginAttempts.setId(View.generateViewId());
        tvLoginAttempts.setText("剩余尝试次数: " + (MAX_LOGIN_ATTEMPTS - loginAttempts));
        tvLoginAttempts.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        tvLoginAttempts.setVisibility(View.GONE);
        ConstraintLayout container = findViewById(R.id.container);
        if (container != null) {
            ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(
                    ConstraintLayout.LayoutParams.WRAP_CONTENT,
                    ConstraintLayout.LayoutParams.WRAP_CONTENT
            );
            params.topToBottom = btnLogin.getId();
            params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
            params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
            params.topMargin = 16;
            container.addView(tvLoginAttempts, params);
        }
        if (progressBar == null) {
            progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleLarge);
            progressBar.setVisibility(View.GONE);
            if (container != null) {
                ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(
                        ConstraintLayout.LayoutParams.WRAP_CONTENT,
                        ConstraintLayout.LayoutParams.WRAP_CONTENT
                );
                params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
                params.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
                params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
                params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
                container.addView(progressBar, params);
            }
        }
    }
    private void setupListeners() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearErrors();
                loginUser();
            }
        });
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }
        });
    }
    private void clearErrors() {
        tilUsername.setError(null);
        tilPassword.setError(null);
    }
    private void loginUser() {
        // 检查是否被锁定
        if (isLocked) {
            Snackbar.make(mainContainer, "账户暂时被锁定，请稍后再试", Snackbar.LENGTH_LONG).show();
            return;
        }
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            tilUsername.setError(getString(R.string.error_empty_fields));
            return;
        }
        if (TextUtils.isEmpty(password)) {
            tilPassword.setError(getString(R.string.error_empty_fields));
            return;
        }
        if (!USERNAME_PATTERN.matcher(username).matches()) {
            tilUsername.setError("用户名必须为4-20位字母、数字或下划线");
            return;
        }
        if (!PASSWORD_PATTERN.matcher(password).matches()) {
            tilPassword.setError("密码必须为6-20位字母、数字或特殊字符");
            return;
        }
        showLoading(true);
        apiService.login(username, password, new ApiService.ApiCallback<Map<String, Object>>() {
            @Override
            public void onSuccess(Map<String, Object> data) {
                runOnUiThread(() -> {
                    showLoading(false);
                    loginAttempts = 0;
                    tvLoginAttempts.setVisibility(View.GONE);
                    try {
                        Map<String, Object> responseData = (Map<String, Object>) data.get("data");
                        if (responseData == null) {
                            System.out.println("服务器返回的数据格式无效");
                            showAuthError("服务器返回的数据格式无效");
                            return;
                        }
                        Map<String, Object> userData = (Map<String, Object>) responseData.get("user");
                        String token = (String) responseData.get("accessToken");
                        if (userData == null || token == null) {
                            System.out.println("服务器返回的用户数据无效");
                            showAuthError("服务器返回的用户数据无效");
                            return;
                        }
                        User user = new User();
                        user.setId(userData.get("id").toString());
                        user.setUsername((String) userData.get("username"));
                        user.setDisplayName((String) userData.get("fullName"));
                        user.setAvatarUrl((String) userData.get("avatarUrl"));
                        user.setEmail((String) userData.get("email"));
                        user.setPhoneNumber((String) userData.get("phoneNumber"));
                        sessionManager.createLoginSession(user, token);
                        Toast.makeText(LoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                        fetchUserDataAndStartMainActivity();
                    } catch (Exception e) {
                        Log.e(TAG, "登录成功但处理用户数据时出错", e);
                        showAuthError("登录成功但处理用户数据时出错");
                    }
                });
            }
            @Override
            public void onFailure(ApiError error) {
                runOnUiThread(() -> {
                    showLoading(false);
                    loginAttempts++;
                    tvLoginAttempts.setVisibility(View.VISIBLE);
                    tvLoginAttempts.setText("剩余尝试次数: " + (MAX_LOGIN_ATTEMPTS - loginAttempts));
                    String errorMsg;
                    if (error.getCode() == 0) {
                        errorMsg = "网络连接问题，请检查网络设置";
                    } else if (error.getCode() == 401) {
                        errorMsg = "用户名或密码错误";
                        tilPassword.setError(errorMsg);
                    } else {
                        errorMsg = error.getMessage();
                    }
                    Snackbar.make(mainContainer, "登录失败: " + errorMsg, Snackbar.LENGTH_LONG).show();
                    if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
                        lockAccount();
                    }
                });
            }
        });
    }
    private void fetchUserDataAndStartMainActivity() {
        final AtomicInteger tasksCompleted = new AtomicInteger(0);
        final int totalTasks = 3; // 联系人、好友列表和好友请求三个任务
        runOnUiThread(() -> {
            showLoading(true);
            Toast.makeText(LoginActivity.this, "正在同步数据...", Toast.LENGTH_SHORT).show();
        });

        // 初始化WebRTC和信令服务
        User currentUser = sessionManager.getUser();
        if (currentUser != null) {
            initializeMediaCommunication(currentUser.getUsername());
        }

        new Thread(() -> {
            try {
                Log.d(TAG, "开始获取联系人数据");
                contactRepository.fetchContactsFromServer();
                Log.d(TAG, "联系人数据获取完成");
            } catch (Exception e) {
                Log.e(TAG, "获取联系人数据时发生异常: " + e.getMessage(), e);
            } finally {
                if (tasksCompleted.incrementAndGet() == totalTasks) {
                    runOnUiThread(() -> startMainActivity());
                }
            }
        }).start();
        new Thread(() -> {
            try {
                Log.d(TAG, "开始获取好友列表数据");
                contactRepository.fetchFriendsFromServer();
                Log.d(TAG, "好友列表数据获取完成");
            } catch (Exception e) {
                Log.e(TAG, "获取好友列表数据时发生异常: " + e.getMessage(), e);
            } finally {
                if (tasksCompleted.incrementAndGet() == totalTasks) {
                    runOnUiThread(() -> startMainActivity());
                }
            }
        }).start();
        new Thread(() -> {
            try {
                Log.d(TAG, "开始获取好友请求数据");
                friendRequestRepository.fetchPendingRequestsFromServer();
                Log.d(TAG, "好友请求数据获取完成");
            } catch (Exception e) {
                Log.e(TAG, "获取好友请求数据时发生异常: " + e.getMessage(), e);
            } finally {
                if (tasksCompleted.incrementAndGet() == totalTasks) {
                    runOnUiThread(() -> startMainActivity());
                }
            }
        }).start();
        new Handler().postDelayed(() -> {
            if (tasksCompleted.get() < totalTasks) {
                Log.w(TAG, "数据同步超时，强制启动主界面");
                runOnUiThread(() -> {
                    Toast.makeText(LoginActivity.this, "部分数据同步未完成，将在后台继续同步", Toast.LENGTH_SHORT).show();
                    startMainActivity();
                });
            }
        }, 150000); // 15秒超时
    }
    private void lockAccount() {
        isLocked = true;
        tvLoginAttempts.setText("账户已锁定，请稍后再试");
        btnLogin.setEnabled(false);
        new AlertDialog.Builder(this)
                .setTitle("账户暂时锁定")
                .setMessage("因多次登录失败，账户已被锁定30秒，请稍后再试。")
                .setPositiveButton("确定", null)
                .show();
        lockoutTimer = new CountDownTimer(LOCKOUT_DURATION_MS, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int secondsRemaining = (int) (millisUntilFinished / 1000);
                tvLoginAttempts.setText("账户已锁定，" + secondsRemaining + "秒后可再次尝试");
            }
            @Override
            public void onFinish() {
                isLocked = false;
                loginAttempts = 0;
                btnLogin.setEnabled(true);
                tvLoginAttempts.setText("账户已解锁，请重新登录");
                new CountDownTimer(3000, 3000) {
                    @Override
                    public void onTick(long millisUntilFinished) {}
                    @Override
                    public void onFinish() {
                        tvLoginAttempts.setVisibility(View.GONE);
                    }
                }.start();
            }
        }.start();
    }
    private void showAuthError(String message) {
        new AlertDialog.Builder(this)
                .setTitle("认证错误")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }
    private void showLoading(boolean isLoading) {
        if (progressBar != null) {
            progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        }
        btnLogin.setEnabled(!isLoading && !isLocked);
        etUsername.setEnabled(!isLoading && !isLocked);
        etPassword.setEnabled(!isLoading && !isLocked);
        tvRegister.setEnabled(!isLoading);
    }
    private void startMainActivity() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消计时器
        if (lockoutTimer != null) {
            lockoutTimer.cancel();
        }
    }
    // 初始化媒体通信相关服务和连接
    private void initializeMediaCommunication(String username) {
        Log.d(TAG, "初始化媒体通信服务，用户: " + username);
        
        // 启动WebSocket服务
        Intent webSocketServiceIntent = new Intent(this, WebSocketService.class);
        webSocketServiceIntent.putExtra("username", username);
        startService(webSocketServiceIntent);
        
        // 启动通话服务
        Intent callServiceIntent = new Intent(this, CallService.class);
        callServiceIntent.putExtra("username", username);
        startService(callServiceIntent);
        
        // 其他可能的初始化，例如WebRTC客户端
        // APP.initWebRTCClient(getApplicationContext(), username);
    }
    // 清理媒体通信相关资源
    private void cleanupMediaCommunication() {
        Log.d(TAG, "清理媒体通信资源");
        
        // 停止WebSocket服务
        stopService(new Intent(this, WebSocketService.class));
        
        // 停止通话服务
        stopService(new Intent(this, CallService.class));
        
        // 其他清理工作
        // if (APP.getWebRTCClient() != null) {
        //     APP.getWebRTCClient().destroy();
        // }
    }
} 